use std::{process::Command, string::FromUtf8Error, thread, time};

use battery::Battery;
use datetime::DateTime;
use memory::Memory;
use net::NetInfo;

pub mod net;
pub mod battery;
pub mod datetime;
pub mod memory;

// 更新status bar
pub fn set_status_bar() {
    // 更新频率
    let sec = time::Duration::from_secs(2);
    // 电池
    let mut battery = Battery::new();
    // 日期时间
    let mut datetime = DateTime::new();
    // 内存使用情况
    let mut memory = Memory::new();
    // 网速信息
    let mut net_info = NetInfo::new();
    // 展示信息
    let mut msg: String = String::from("");
    loop {
        let display = format!(
            "{} {} {} {}",
            net_info.display(),
            memory.display(),
            battery.display(),
            datetime.display()
        );
        if !msg.eq(display.as_str()) {
            msg = display;
            set_bar(&msg);
        }
        thread::sleep(sec);
    }
}

// 设置状态栏
fn set_bar(msg: &String) {
    let cmd = format!("xsetroot -name ' {} '", msg.replace("\n", ""));
    let res = exec_cmd(cmd.as_str());
    match res {
        Ok(_) => {}
        Err(err) => {
            eprintln!("xsetroot error, err is {}", err);
        }
    }
}

// 执行linux命令
fn exec_cmd(command: &str) -> Result<String, FromUtf8Error> {
    let output = Command::new("/bin/dash")
        .arg("-c")
        .arg(command)
        .output()
        .expect("error");
    let result = String::from_utf8(output.stdout);
    result
}
